#coding:utf8
from rest_framework import serializers
from .models import OAuthQQUser
from django_redis import get_redis_connection
from users.models import User

# serializers.ModelSerializer   ,关联模型没有一点作用,因为我们校验的字段 都没有在模型中
# serializers.Serializer

class QQTokenSerializer(serializers.Serializer):
    """
    1. 当用户点击保存的时候,需要把 access_token(openid),手机号,密码,短信验证码,post过来
    2.  access_token,短信验证码需要进行校验
    3. 需要将 user 和 openid保存入库
    """

    #完成字段
    access_token = serializers.CharField(label='操作token')
    mobile = serializers.RegexField(label='手机号', regex=r'^1[345789]\d{9}$')
    password = serializers.CharField(label='密码', max_length=20, min_length=8)
    sms_code = serializers.CharField(label='短信验证码', max_length=6, min_length=6)

    #完成校验
    def validate(self, attrs):

        #1.access_token
        access_token = attrs.get('access_token')
        openid = OAuthQQUser.openid_by_token(access_token)

        if openid is None:
            raise serializers.ValidationError('openid错误')
        #######################
        #把openid放到 attrs中,验证没有问题之后,attrs其实就变成了 validated_data
        attrs['openid'] = openid

        #2.短信验证码
        sms_code = attrs.get('sms_code')
        mobile = attrs['mobile']
        # I, 连接redis
        redis_conn = get_redis_connection('code')
        # II 获取 redis的短信验证码
        redis_code = redis_conn.get('sms_%s' % mobile)
        if redis_code is None:
            raise serializers.ValidationError('短信验证码过期')
        # III 比较
        if redis_code.decode() != sms_code:
            raise serializers.ValidationError('短信验证码不一致')


        #3. 根据手机号判断用户是否注册过
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            #不存在
            #创建一个
            pass
        else:
            #存在
            #绑定
            #校验密码是否正确
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('您输入的密码不正确')
            #################################
            attrs['user']=user

        return attrs



    def create(self, validated_data):
        # validated_data 是校验之后的数据

        user = validated_data.get('user')

        if user is None:
            # 创建一个
            user = User.objects.create(
                username=validated_data.get('mobile'),
                mobile = validated_data.get('mobile'),
                password=validated_data.get('password')
            )

            user.set_password(validated_data.get('password'))
            user.save()


        #需要将 user 和 openid保存入库

        OAuthQQUser.objects.create(
            user=user,
            openid=validated_data.get('openid')
        )


        return user
